package twitter.functionalities;

import java.util.ArrayList;
import java.util.List;

import twitter4j.IDs;
import twitter4j.Twitter;
import twitter4j.TwitterException;

public class FollowUnfollow {

	private Twitter twitter;
	private static final String USER = "naedius"; // "chiabenzi";
	private List<Long> followerList = new ArrayList<Long>();
	private List<Long> followingList = new ArrayList<Long>();

	public FollowUnfollow(Twitter twitter) {
		this.twitter = twitter;
	}

	public void setUp(String name) throws TwitterException {
		long cursor = -1;
		IDs list;
		// String[] s = { USER };
		// long idUser = twitter.lookupUsers(s).get(0).getId();
		do {
			list = twitter.getFollowersIDs(name, cursor);
			for (int i = 0; i < list.getIDs().length; i++) {
				followerList.add(list.getIDs()[i]);

			}
			cursor = list.getNextCursor();
		} while (cursor != 0);
		cursor = -1;
		boolean flag = false;
		do {
			list = twitter.getFriendsIDs(name, cursor);
			for (int i = 0; i < list.getIDs().length && !flag; i++) {
				followingList.add(list.getIDs()[i]);

			}

			cursor = list.getNextCursor();
		} while (cursor != 0 && !flag);
	}

	public void follow(String screenName) throws TwitterException {
		long cursor = -1;
		IDs list;
		List<Long> followers = new ArrayList<Long>();
		do {
			list = twitter.getFollowersIDs(screenName, cursor);
			for (int i = 0; i < list.getIDs().length; i++) {
				if (!followingList.contains(list.getIDs()[i])) {
					followers.add(list.getIDs()[i]);
				}
			}
			cursor = list.getNextCursor();
		} while (cursor != 0);

		// long[] u = new long[1];
		// System.out.println("follower");
		for (int i = 0; i < followers.size() && i < 499; i++) {
			// u[0] = followers.get(i);
			// System.out.println(twitter.lookupUsers(u).get(0).getScreenName());
			try {
				twitter.createFriendship(followers.get(i));
			} catch (TwitterException e) {
				e.printStackTrace();
			}

		}
	}

	public void unfollow() throws TwitterException {

		// long[] u = new long[1];
		// System.out.println("follower");
		// for (int i = 0; i < 5; i++) {
		// u[0] = followerList.get(i);
		// System.out.println(twitter.lookupUsers(u).get(0).getScreenName());
		// }
		// System.out.println("following");
		// for (int i = 0; i < followingList.size(); i++) {
		// u[0] = followingList.get(i);
		// System.out.println(twitter.lookupUsers(u).get(0).getScreenName());
		// }

		for (int i = 0; i < followingList.size(); i++) {
			boolean isFollower = false;
			for (int j = 0; j < followerList.size() && !isFollower; j++) {
				long juser = followerList.get(j);
				if (juser == followingList.get(i)) {
					isFollower = true;
				}
			}
			if (!isFollower) {
				// u[0] = followingList.get(i);
				// System.out.println(twitter.lookupUsers(u).get(0)
				// .getScreenName());
				twitter.destroyFriendship(followingList.get(i));
			}
		}

	}
}
